<template>
  <view 
    class="w-full bg-gradient-to-b from-[#B0ED90] to-[#3CEBBB] rounded-b-[16rpx] flex 
    justify-start items-end px-[20rpx] pb-[18rpx] box-border"
    :style="{ height: headerHeight + 'px', paddingTop: statusBarHeight + 'px' }"
  >
    <view class="flex items-center">
      <!-- 头像 -->
      <view class="w-[170rpx] h-[170rpx] bg-white rounded-[50%] overflow-hidden" @click="handleClickAvatar()">
        <image 
          :src="(tokenStore.hasLogin&&userStore.userInfo.avatar) ? getEnvBaseUrl() + userStore.userInfo.avatar : '/static/images/logo2.png'" 
          class="w-full h-full"
          mode="aspectFill"
        />
      </view>
      <!-- 用户名和下方的标签 -->
      <view class="ml-[28rpx]">
        <view class="text-[40rpx] font-bold color-[#003309] mb-[20rpx]">
          {{ tokenStore.hasLogin ? (userStore.userInfo.username || '--') : '未登录' }}
        </view>
        <view v-if="tokenStore.hasLogin" class="flex items-center">
          <!-- <view class="label">账号设置</view> -->
          <view class="label">{{ userStore.userInfo.realname || '--' }}</view>
        </view>
      </view>
    </view>
  </view>
  <!-- 下方的菜单 -->
  <view class="px-[24rpx]">
    <view class="menu-item">
      <text>累计学习：{{ tokenStore.hasLogin ? formatStudyDuration(userStore.userInfo.study_duration) : '--' }}</text>
    </view>
    <view class="menu-item" @click="handleClick('1')">
      <text>学习进度</text>
      <wd-icon name="arrow-right" size="22px" color="#282828"></wd-icon>
    </view>
    <view class="menu-item" @click="handleClick('2')">
      <text>错题库</text>
      <wd-icon name="arrow-right" size="22px" color="#282828"></wd-icon>
    </view>
    <view class="menu-item" @click="handleClick('3')">
      <text>售后</text>
      <wd-icon name="arrow-right" size="22px" color="#282828"></wd-icon>
    </view>
    <view class="menu-item" style="border-bottom: none;" @click="handleClick('4')">
      <text>在线客服</text>
      <wd-icon name="arrow-right" size="22px" color="#282828"></wd-icon>
    </view>
    
    <!-- 退出登录按钮 -->
    <view 
      v-if="tokenStore.hasLogin" 
      class="logout-btn" 
      @click="handleLogout"
    >
      <text>退出登录</text>
    </view>

  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { useTokenStore } from '@/store/token'
import { getEnvBaseUrl } from '@/utils'

defineOptions({
  name: 'My',
})
definePage({
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '我的',
  },
})

// 获取用户信息和登录状态
const userStore = useUserStore()
const tokenStore = useTokenStore()

// 页面显示时检查登录状态并重新获取用户信息
onShow(() => {
  if (!tokenStore.hasLogin) {
    // uni.showToast({
    //   title: '请先登录',
    //   icon: 'none',
    //   duration: 1500,
    // })
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/index?redirect=/pages/my/index'
      })
    }, 500)
  } else {
    // 用户已登录，重新获取最新的用户信息
    userStore.fetchUserInfo()
  }
})

// 获取系统信息
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = ref(systemInfo.statusBarHeight || 0)

// 基础高度（原来的 296rpx 转换为 px）+ 状态栏高度
const baseHeight = computed(() => {
  // 296rpx 按照设计稿 750rpx 宽度计算
  const rpxToPx = systemInfo.windowWidth / 750
  return 296 * rpxToPx
})

const headerHeight = computed(() => {
  return baseHeight.value + statusBarHeight.value
})

// 格式化学习时长（后端返回的是秒数）
const formatStudyDuration = (seconds) => {
  if (!seconds || seconds === 0) {
    return '0小时'
  }
  
  // 将秒数转换为小时和分钟
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0 && minutes > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (hours > 0) {
    return `${hours}小时`
  } else if (minutes > 0) {
    return `${minutes}分钟`
  } else {
    return `${seconds}秒`
  }
}

const handleClickAvatar = () => {
  if (!tokenStore.hasLogin) {
    uni.navigateTo({
      url: '/pages/login/index',
    })
  } else {
    // 跳转到用户信息页面
  }
}

const handleClick = (type) => {
  let url = ''
  if (type === '1') { // 学习进度
    url = '/pages-children/productListByStudy/index'
  } else if (type === '2') { // 错题库
    url = '/pages-children/wrongQuestionBank/index'
  } else if (type === '3') { // 售后
    url = '/pages-children/afterSales/index'
  } else if (type === '4') { // 在线客服
    url = ''
  }
  uni.navigateTo({
    url: url,
  })
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除本地存储
        uni.removeStorageSync('accessTokenExpireTime')
        uni.removeStorageSync('refreshTokenExpireTime')
        uni.removeStorageSync('token')
        // 清除pinia
        tokenStore.tokenInfo = {}
        userStore.clearUserInfo()
        // 跳转到首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }, 100)
        // setTimeout(() => {
        //   uni.showToast({
        //     title: '已退出登录',
        //     icon: 'none',
        //     duration: 1500
        //   })
        // }, 500);
      }
    }
  })
}
</script>

<style>
page{
  background-color: #F1F1F1;
}
</style>

<style lang="scss" scoped>
.label {
  background: #BBFFC1;
  border-radius: 50rpx;
  padding: 0rpx 16rpx;
  margin-right: 16rpx;
  box-shadow: border-box;

  font-size: 28rpx;
  color: #282828;
  line-height: 56rpx;
  // text-shadow: 2px 0px 2px #000000;
}
.menu-item {
  font-weight: 400;
  font-size: 32rpx;
  color: #282828;
  line-height: 56rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1.5rpx solid #E0E0E0;
  padding: 20rpx 5rpx;
  text {
    position: relative;
    top:2rpx;
  }
}
.logout-btn {
  margin-top: 40rpx;
  margin-bottom: 40rpx;
  font-weight: 400;
  font-size: 32rpx;
  color: #FF4444;
  line-height: 56rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 5rpx;
  text {
    position: relative;
    top:2rpx;
  }
}
</style>
